<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="600"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div>
      <el-form label-width="120px" :model="form" :rules="rules" ref="formRef">
        <el-row>
          <el-col :span="22">
            <el-form-item :label="t('business.refund.customerId')" prop="customerId">
              <select-customer
                v-model="form.customerId"
                @update:model-value="handleCustomerChange"
                :placeholder="t('business.refund.placeholder.customerId')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item :label="t('business.customer.balanceAmount')" prop="balanceAmount">
              {{form.balanceAmount}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item :label="t('business.refund.amount')" prop="amount">
              <el-input-number
                v-model="form.amount"
                :min="0.01"
                :max="Number(form.balanceAmount)"
                :precision="2"
                style="width: 200px"
                :placeholder="t('business.refund.placeholder.amount')"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="22">
            <el-form-item :label="t('crud.table.column.note')" prop="note">
              <el-input type="textarea" rows="5" v-model="form.note" :placeholder="t('crud.table.column.note')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose" :loading="state.loading">{{t('crud.cancelText')}}</el-button>
      <el-button @click="handleSubmit" type="primary" :loading="state.loading">{{t('crud.confirmText')}}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {useI18n} from 'vue-i18n'

import {RefundBo} from '@/api/business/refund/types'
import {add} from '@/api/business/refund'
import {getDetail as customerDetail} from '@/api/business/customer'
import { FormInstance, FormRules } from 'element-plus'

const { t } = useI18n()

const emits = defineEmits(['success'])

const state = reactive({
  visible: false,
  loading: false,
  recharge: {},
  title: t('business.refund.action.add'),
  page: {
    pageSize: 30,
    pageNum: 1,
  },
  total: 0,
  query: {},
})

const refund = {
  id: undefined,
  customerId: '',
  balanceAmount: '0.00',
  amount: undefined,
  note: '',
}

const form = ref<RefundBo>(refund)

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  customerId: [{ required: true, message: t('business.refund.validator.customerId'), trigger: 'blur' }],
  amount: [{ required: true, message: t('business.refund.validator.amount'), trigger: 'blur' }],
})

const openDialog = () => {
  state.visible = true
  form.value = refund
}

const handleClose = () => {
  state.visible = false
}

const handleCustomerChange = (customerId: string) => {
  if(customerId) {
    loadCustomer()
  }
}

const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})

const loadCustomer = () => {
  customerDetail(form.value.customerId).then((res: any) => {
    form.value.balanceAmount = res.data.balanceAmount
  })
}

const handleSubmit = () => {
  formRef.value?.validate(async (isValid) => {
    if(isValid) {
      state.loading = true
      let data = Object.assign({}, form.value)
      add(toRaw(data)).then(()=>{
        ElMessage.success(t('operate.tooltip.success'))
        emits('success')
        handleClose()
      }).finally(()=>{
        state.loading = false
      })
    }
  })
}
</script>
